package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    /**
     * 添加购物车
     *
     * @param shoppingCart 购物车对象
     * @return Boolean
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //1.查询当前商品在购物车是否存在
        ShoppingCart dbShoppingCart = shoppingCartMapper.queryCart(shoppingCart);
        if (dbShoppingCart!=null){
            //已存在商品，设置数量+1
            dbShoppingCart.setNumber(dbShoppingCart.getNumber()+1);
            shoppingCartMapper.increaseNumber(dbShoppingCart.getId(), dbShoppingCart.getNumber());
        }else {
            //新的商品，添加到购物车设置数量为1
            dbShoppingCart=shoppingCart;
            dbShoppingCart.setNumber(1);
            dbShoppingCart.setUserId(shoppingCart.getUserId());
            dbShoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.add(dbShoppingCart);
        }
        return dbShoppingCart;
    }

    /**
     * 减少商品数量
     *
     * @param shoppingCart 购物车对象
     * @return Boolean
     */
    @Override
    public ShoppingCart decreaseNumber(ShoppingCart shoppingCart) {
        //1.查询当前商品在购物车是否存在
        ShoppingCart dbShoppingCart = shoppingCartMapper.queryCart(shoppingCart);

        if (dbShoppingCart.getNumber()>1){

            dbShoppingCart.setNumber(dbShoppingCart.getNumber()-1);
            shoppingCartMapper.decreaseNumber(dbShoppingCart.getId(), dbShoppingCart.getNumber());
        }else {
            //商品数量为1时直接删除商品
             dbShoppingCart.setNumber(dbShoppingCart.getNumber()-1);
            shoppingCartMapper.deleteById(dbShoppingCart);
        }

        return dbShoppingCart;
    }


    /**
     * 查询购物车列表：
     *
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCart> findShoppingCartListByUserId(Long userId) {
        return shoppingCartMapper.findShoppingCartListByUserId(userId);
    }

    /**
     * 根据用户id清空购物车
     *
     * @param userId
     * @return
     */
    @Override
    public Integer delete(Long userId) {
        return shoppingCartMapper.delete(userId);
    }


}
